package cn.diancan.Tags.utils;

import java.io.File;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.beanutils.ConvertUtilsBean;
import org.apache.commons.beanutils.Converter;
import org.springframework.util.Assert;



import freemarker.core.Environment;
import freemarker.template.ObjectWrapper;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateNumberModel;
import freemarker.template.utility.DeepUnwrap;

/**
 * 前台工具类
 * 
 * @author zhenglong
 */
public class FrontUtils {
	
	public static final String SYSTEM_CONFIG_THEME_KEY = "systemTheme";// systemConfig缓存Key
	public static final String SPT = File.separator;
	public static final String THEME = "theme";
	private static final ConvertUtilsBean convertUtilsBean;
	
	static  {
		convertUtilsBean = new ConvertUtilsBean();
	}
	
	/**
	 * 传入参数，列表样式。
	 */
	public static final String PARAM_STYLE_LIST = "styleList";
	/**
	 * 站点
	 */
	public static final String SITE = "site";
	/**
	 * 总条数
	 */
	public static final String COUNT = "count";
	/**
	 * 页码
	 */
	public static final String PAGE_NO = "pageNo";
	/**
	 * 页面翻页地址
	 */
	public static final String HREF = "href";
	/**
	 * href前半部（相对于分页）
	 */
	public static final String PAGE_LINK = "pageLink";
	/**
	 * href后半部（相对于分页）
	 */
	public static final String PAGE_SUFFIX = "pageSuffix";
	/**
	 * 起始条数
	 */
	public static final String FIRST = "first";
	/**
	 * UTF-8编码
	 */
	public static final String UTF8 = "UTF-8";
	/**
	 * 页面完整地址
	 */
	public static final String LOCATION = "location";
	/**
	 * 部署路径
	 */
	public static final String BASE = "base";
	/**
	 * 站点
	 */
	public static final String WEB = "web";
	
	@SuppressWarnings("rawtypes")
	public static Object getParameter(String name, Class type, Map params) {
		Assert.hasText(name);
		Assert.notNull(type);
		Assert.notNull(params);
		TemplateModel templatemodel = (TemplateModel)params.get(name);
		if (templatemodel == null) {
			return null;
		} else {
			Object obj = null;
			try {
				obj = DeepUnwrap.unwrap(templatemodel);
			} catch (TemplateModelException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return convertUtilsBean.convert(obj.toString(),type);
		}
	}
	
	public static TemplateModel getVariable(String name, Environment env) throws TemplateModelException {
		Assert.hasText(name);
		Assert.notNull(env);
		return env.getVariable(name);
	}
	
	public static void setVariable(String name, Object value, Environment env) throws TemplateModelException{
		Assert.hasText(name);
		Assert.notNull(env);
		if (value instanceof TemplateModel){
			env.setVariable(name, (TemplateModel)value);
		} else {
			env.setVariable(name, ObjectWrapper.BEANS_WRAPPER.wrap(value));
		}
	}
	
	@SuppressWarnings("rawtypes")
	public static void setVariables(Map variables, Environment env) throws TemplateModelException {
		Assert.notNull(variables);
		Assert.notNull(env);
		for (Iterator iterator = variables.entrySet().iterator(); iterator.hasNext();){
			Map.Entry entry = (Map.Entry)iterator.next();
			String s = (String)entry.getKey();
			Object obj = entry.getValue();
			if (obj instanceof TemplateModel){
				env.setVariable(s, (TemplateModel)obj);
			} else {
				env.setVariable(s, ObjectWrapper.BEANS_WRAPPER.wrap(obj));
			}
		}

	}
	
	/**
	 * 标签参数中获得条数。
	 * @param params
	 * @return 如果不存在，或者小于等于0，或者大于5000则返回5000；否则返回条数。
	 * @throws TemplateException
	 */
	public static int getCount(Map<String, TemplateModel> params)
			throws TemplateException {
		Integer count = DirectiveUtils.getInt(COUNT, params);
		if (count == null || count <= 0 || count >= 5000) {
			return 5000;
		} else {
			return count;
		}
	}
	
	/**
	 * 标签中获得页码
	 * 
	 * @param env
	 * @return
	 * @throws TemplateException
	 */
	public static int getPageNo(Environment env) throws TemplateException {
		TemplateModel pageNo = env.getGlobalVariable(PAGE_NO);
		if (pageNo instanceof TemplateNumberModel) {
			return ((TemplateNumberModel) pageNo).getAsNumber().intValue();
		} else {
			throw new TemplateModelException("'" + PAGE_NO
					+ "' not found in DataModel.");
		}
	}

	public static int getFirst(Map<String, TemplateModel> params)
			throws TemplateException {
		Integer first = DirectiveUtils.getInt(FIRST, params);
		if (first == null || first <= 0) {
			return 0;
		} else {
			return first - 1;
		}
	}
	
}
